// Node server to monitor the parking lot database
// and update connected clients with any changes.

var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app),
    fs = require('fs'),
    mysql = require('mysql'),
    dbConnection = mysql.createConnection({
      host     : 'localhost',
      user     : 'plms_user',
      password : 'p1m5us3r',
      database : 'plms'
    }),
    POLLING_INTERVAL = 1000,
    pollingTimer,
    prevQueryTime = 1;

dbConnection.connect(function(err) {
  console.log(err);
});

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

var pollingLoop = function () {
    if (io.sockets.clients().length) {
      pollingTimer = setTimeout( pollingLoop, POLLING_INTERVAL );
      console.log("Updating clients, prevQueryTime=" + prevQueryTime);
      updateSockets(prevQueryTime, null);
    }
};

io.sockets.on( 'connection', function ( socket ) {
    console.log( 'A new socket is connected!' );
    updateSockets(0, socket);
    if (io.sockets.clients().length) {
      pollingLoop();
    }
});

var updateSockets = function ( time, socket ) {
  console.log("Entered updateSockets()");
    var query = dbConnection.query('SELECT row_id,status,updated FROM parking_lot WHERE updated > ' + time),
      data = [], // this array will contain the result of our db query
      newTime = 0;

  query
  .on('error', function(err) {
    console.log( err );
    // updateSockets( err );
  })
  .on('result', function(space) {
    data.push({
      index : space.row_id,
      color : (space.status == 0 ? "0C0" : "C00")
    });
    newTime = Math.max(newTime, space.updated);
  })
  .on('end',function(){
    console.log("Finished db query, prevQueryTime=" + prevQueryTime);
    if (time === 0) {
      console.log('Sending data to new client');
      socket.volatile.emit('update', data);
    } else if (data.length > 0) {
      console.log('Broadcasting data');
      io.sockets.volatile.emit('update', data);
      console.log('newTime='+newTime);
      prevQueryTime = newTime;
    }
  });
};
